const Koa = require('koa')
const app = new Koa()
const error = require('koa-json-error')
// const bodyParser = require('body-parser')
const parameter = require('koa-parameter')
const path = require('path')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const router = require('./routes')
const { db } = require('./config')
const mongoose = require('mongoose')

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }, () => {
  console.log('mongodb connected')
})
mongoose.connection.on('error', console.error)
// 鉴权
// const auth = async (ctx, next) => {
//   if (ctx.url !== '/users') {
//     ctx.throw(401)
//   }
//   await next()
// }

// koa-static 为静态文件生成 http 链接  
app.use(koaStatic(path.join(__dirname, 'public')))
app.use(error({
  postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}))
app.use(koaBody({
  // 启用文件
  multipart: true,
  // koa-body 引用的一个 npm 包，用于配置上传相关 
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'),
    keepExtensions: true // 保留文件拓展名
  }
}))
app.use(parameter(app))
// parse application/x-www-form-urlencoded
// app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json
// app.use(bodyParser.json())
router(app)
// app.use(auth)
app.listen(3000)